package com.example.zhoutao.puzzle.Gaming;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.example.zhoutao.puzzle.Data.HistoryDataManager;
import com.example.zhoutao.puzzle.Data.UserDataManager;
import com.example.zhoutao.puzzle.Dialog.SelectImageDialog;
import com.example.zhoutao.puzzle.Login.Login;
import com.example.zhoutao.puzzle.R;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author ZT on 2019.4
 * @Description 菜单界面
 */
public class GameMenu extends AppCompatActivity {

    private static final int TAKE_PHOTO = 100;// 拍照
    private static final int CROP_PHOTO = 12;// 裁剪图片
    private static final int LOCAL_CROP = 13;// 本地图库
    private Uri imageUri;// 拍照时的图片uri
    private SelectImageDialog selectImageDialog;
    private int MusicFlag = 0;
    private String name;
    private int MusicFlag1=0;
    private  UserDataManager mUserDataManager;
    private boolean set_flag;
    private String set_diff="3";
    private String set_mode="Normal";
    private String set_music="on";
    private boolean FirstCome=true;
    private Cursor cursor;

    private String[] diff={"3","4","5","6","7"};
    private String[] mode={"Easy","Normal","Hard"};
    private String[] music={"on","off"};
    private NumberPicker numberPicker_diff,numberPicker_mode,numberPicker_music;
    private String getDiff,getMode,getMusic;
    private AlertDialog.Builder set_dialog;
    private boolean isSet_flag;

    public static List<Activity> activityList = new LinkedList<>();
    Button btn_Start, btn_history, btn_Set, btn_About, btn_Quit, btn_Quit_Login;
    int flag;
    private File takePhotoImage;
    private int WRITE_PERMISSION=0x01;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_menu);
        GameMenu.activityList.add(this);
        requestWritePermission();
        //获取数据
        Intent intent=getIntent();
        //从intent取出bundle
        Bundle bundle=intent.getBundleExtra("res");
        name = bundle.getString("name");
        MusicFlag1=bundle.getInt("MusicFlag");

        btn_Start = findViewById(R.id.GameStart);
        btn_history = findViewById(R.id.GameHistory);
        btn_Set = findViewById(R.id.GameSet);
        btn_About = findViewById(R.id.GameAbout);
        btn_Quit = findViewById(R.id.GameQuit);
        btn_Quit_Login = findViewById(R.id.GameQuit_Login);


        if (mUserDataManager == null) {
            mUserDataManager = new UserDataManager(this);
            mUserDataManager.openDataBase();                              //建立本地数据库
        }
        cursor=mUserDataManager.fetchUserDefaultByName(name);
        cursor.moveToNext();
        set_music=cursor.getString(5);
        Log.i("音乐打开？", set_music);
        if (set_music.equals("on")){
            MusicStart();
        }else{
            MusicStop();
        }


        //为按钮绑定事件
        btn_Start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                takePhotoOrSelectPicture();

            }
        });

        btn_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GameMenu.this, GameHistory.class);
                bundle.putString("name",name);
                intent.putExtra("res",bundle);
                startActivity(intent);
            }
        });

        btn_Set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //对话框设置音乐
                //showPopMenu(v);
                set_dialog=createSetDialog(GameMenu.this,"");
                set_dialog.create().show();

            }
        });


        btn_Quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicStop();
                exit();
            }
        });

        btn_Quit_Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GameMenu.this, Login.class);
                startActivity(intent);
            }
        });
    }

    //退出程序
    public void exit() {
        for (Activity act : activityList) {
            act.finish();
        }
        System.exit(0);
    }

    //关于弹出的对话框
    public void showDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("关于");
        builder.setMessage("Author:ZhouTao" + "\n" + "School:WuHan University of Technology" + "\n" + "Version:Puzzle v1.0");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //点击设置弹出选择框
    public void showPopMenu(View view) {
        PopupMenu menu = new PopupMenu(this, view);
        menu.getMenuInflater().inflate(R.menu.game_set, menu.getMenu());
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.turn_on:
                        MusicStart();
                        Toast.makeText(GameMenu.this, "音乐已打开", Toast.LENGTH_SHORT).show();
                        MusicFlag = 0;
                        break;

                    case R.id.turn_off:
                        MusicStop();
                        Toast.makeText(GameMenu.this, "音乐已关闭", Toast.LENGTH_SHORT).show();
                        MusicFlag = 1;
                        break;

                    case R.id.default_set:


                }
                return true;
            }
        });
        menu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                //Toast.makeText(GameMenu.this,"未设置",Toast.LENGTH_SHORT).show();
            }
        });
        menu.show();
    }

    public void MusicStart() {
        Intent intent = new Intent(this, MusicSever.class);
        startService(intent);
    }

    public void MusicStop() {
        Intent intent = new Intent(this, MusicSever.class);
        stopService(intent);
    }

    private void takePhotoOrSelectPicture() {
        CharSequence[] items = {"拍照", "图库", "默认图片"};// 裁剪items选项

        // 弹出对话框提示用户拍照或者是通过本地图库选择图片
        new AlertDialog.Builder(GameMenu.this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        flag = 1;
                        switch (which) {

                            // 选择了拍照
                            case 0:
                                 // 创建文件保存拍照的图片
                                 takePhotoImage = new File(Environment.getExternalStorageDirectory()+"/DCIM", "take_photo_image.jpg");
                                 try {
                                 // 文件存在，删除文件
                                 if(takePhotoImage.exists()){
                                 takePhotoImage.delete();
                                 }
                                 // 根据路径名自动的创建一个新的空文件
                                 takePhotoImage.createNewFile();
                                 }catch (Exception e){
                                 e.printStackTrace();
                                 }
                                 // 获取图片文件的uri对象
                                 imageUri = Uri.fromFile(takePhotoImage);
                                 // 创建Intent，用于启动手机的照相机拍照
                                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                 // 指定输出到文件uri中
                                 intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

                                 //取消严格模式 FileProvider
                                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                 StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                                 StrictMode.setVmPolicy( builder.build() );
                                 }

                                 //插入到图库


                                 // 启动intent开始拍照
                                 startActivityForResult(intent, TAKE_PHOTO);
                                 break;

                                // 调用系统图库
                            case 1:

                                // 创建Intent，用于打开手机本地图库选择图片
                                Intent intent1 = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                // 启动intent打开本地图库
                                startActivityForResult(intent1, LOCAL_CROP);
                                break;

                            //游戏自带图片
                            case 2:
                                if (selectImageDialog == null) {
                                    selectImageDialog = new SelectImageDialog();
                                    selectImageDialog.addItemClickListener(new SelectImageDialog.OnItemClickListener() {
                                        @Override
                                        public void itemClick(int position, int res) {
                                            //更新布局
                                            // 实例化一个Bundle
                                            Bundle bundle = new Bundle();
                                            // 实例化一个intent
                                            Intent intent2 = new Intent(GameMenu.this, PuzzleGame.class);
                                            // 获取输入的数据,把数据保存到Bundle里
                                            bundle.putInt("res_default", res);
                                            bundle.putInt("changeImgFlag", 0);
                                            bundle.putString("name",name);
                                            // 把bundle放入intent里
                                            intent2.putExtra("res", bundle);
                                            startActivity(intent2);
                                            finish();

                                        }
                                    });
                                }
                                selectImageDialog.showDialog(getFragmentManager(), "dialog", 0);

                        }

                    }
                }).show();
    }


    /**
     * 调用startActivityForResult方法启动一个intent后，
     * 可以在该方法中拿到返回的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        switch (requestCode) {

            case TAKE_PHOTO:// 拍照

                if (resultCode == RESULT_OK) {

                    // 创建intent用于裁剪图片
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    // 设置数据为文件uri，类型为图片格式
                    intent.setDataAndType(imageUri, "image/*");
                    // 允许裁剪
                    intent.putExtra("scale", true);
                    // 指定输出到文件uri中
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                    //把图片插入到系统图库
                    try{
                        MediaStore.Images.Media.insertImage(this.getContentResolver(),takePhotoImage.getAbsolutePath(),"take_photo_image.jpg",null);
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }

                    //通知图库更新
                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.parse(takePhotoImage.getAbsolutePath())));
                    // 启动intent，开始裁剪
                    startActivityForResult(intent, CROP_PHOTO);
                    break;
                }
                break;
            case LOCAL_CROP:// 系统图库

                if (resultCode == RESULT_OK) {
                    // 创建intent用于裁剪图片
                    Intent intent1 = new Intent("com.android.camera.action.CROP");
                    // 获取图库所选图片的uri
                    Uri uri = data.getData();
                    intent1.setDataAndType(uri, "image/*");
                    //  设置裁剪图片的宽高
                    intent1.putExtra("outputX", 300);
                    intent1.putExtra("outputY", 300);
                    // 裁剪后返回数据
                    intent1.putExtra("return-data", true);
                    // 启动intent，开始裁剪
                    startActivityForResult(intent1, CROP_PHOTO);

                }

                break;
            case CROP_PHOTO:// 裁剪后展示图片
                if (resultCode == RESULT_OK) {
                    try {

                        // 展示拍照后裁剪的图片
                        if (imageUri != null) {
                             // 创建BitmapFactory.Options对象
                             BitmapFactory.Options option = new BitmapFactory.Options();
                             //属性设置，用于压缩bitmap对象
                             option.inSampleSize = 4;
                             option.inPreferredConfig = Bitmap.Config.RGB_565;
                             // 根据文件流解析生成Bitmap对象
                             //Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                             //Bitmap bitmap=data.getExtras().getParcelable("data");
                            // 展示图片
                            // iv_text.setImageBitmap(bitmap);
                            Bitmap bitmap1=BitmapFactory.decodeFile(imageUri.getPath());
                            Bitmap bitmap=compressScale(bitmap1);

                            // 实例化一个Bundle
                            Bundle bundle = new Bundle();
                            // 实例化一个intent
                            Intent intent = new Intent(GameMenu.this, PuzzleGame.class);
                            // 获取输入的数据,把数据保存到Bundle里
                            bundle.putParcelable("res_default", bitmap);
                            bundle.putInt("changeImgFlag", 1);
                            bundle.putString("name",name);
                            // 把bundle放入intent里
                            intent.putExtra("res", bundle);

                            startActivity(intent);
                            finish();



                        }


                        // 展示图库中选择裁剪后的图片
                        if (data != null) {
                            // 根据返回的data，获取Bitmap对象
                            Bitmap bitmap = data.getExtras().getParcelable("data");
                            // 实例化一个Bundle
                            Bundle bundle = new Bundle();
                            // 实例化一个intent
                            Intent intent = new Intent(GameMenu.this, PuzzleGame.class);
                            // 获取输入的数据,把数据保存到Bundle里
                            bundle.putParcelable("res_default", bitmap);
                            bundle.putInt("changeImgFlag", 1);
                            bundle.putString("name",name);
                            // 把bundle放入intent里
                            intent.putExtra("res", bundle);
                            startActivity(intent);
                            finish();

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("报错", "Text");
                    }
                }
                break;

        }

    }

    //获得存储权限
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if(requestCode == WRITE_PERMISSION){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("", "Write Permission Failed");
                Toast.makeText(this, "You must allow permission write external storage to your mobile device.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void requestWritePermission(){
        if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
        }
    }

    /**
     * 图片按比例大小压缩方法
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        Log.i("", w + "---------------" + h);
        float hh = 200f;
        float ww = 200f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
        //return bitmap;
    }

    /**
     * 质量压缩方法
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 40) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    //设置对话框
    public AlertDialog.Builder createSetDialog(Context context,String msg){
        LayoutInflater inflater=LayoutInflater.from(context);
        View v=inflater.inflate(R.layout.default_set,null);
        numberPicker_diff=v.findViewById(R.id.np_diff);
        numberPicker_mode=v.findViewById(R.id.np_mode);
        numberPicker_music=v.findViewById(R.id.np_music);

        //默认关卡
        numberPicker_diff.setDisplayedValues(diff);
        numberPicker_diff.setMinValue(0);
        numberPicker_diff.setMaxValue(diff.length-1);
        numberPicker_diff.setOnValueChangedListener(diffChangedListener);

        //默认模式
        numberPicker_mode.setDisplayedValues(mode);
        numberPicker_mode.setMinValue(0);
        numberPicker_mode.setMaxValue(mode.length-1);
        numberPicker_mode.setOnValueChangedListener(modeChangedListener);

        //音乐设置
        numberPicker_music.setDisplayedValues(music);
        numberPicker_music.setMinValue(0);
        numberPicker_music.setMaxValue(music.length-1);
        numberPicker_music.setOnValueChangedListener(musicChangedListener);

        AlertDialog.Builder setDialog= new AlertDialog.Builder(context);
        setDialog.setMessage("设置");
        setDialog.setView(v);
        //不可用返回键取消
        setDialog.setCancelable(false);
        setDialog.setPositiveButton("完成",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        set_diff=getDiff;
                        set_mode=getMode;
                        set_music=getMusic;
                        Log.i("设置结果：", getDiff+getMode+getMusic);
                        isSet_flag=mUserDataManager.UpdateUserSet(set_diff,set_mode,set_music);
                        if (isSet_flag){
                            Toast.makeText(GameMenu.this, "设置完成", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(GameMenu.this, "设置未完成", Toast.LENGTH_SHORT).show();
                        }
                        if (set_music == "on") {
                            MusicStart();
                        }else{
                            MusicStop();
                        }
                    }
                });
        setDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        return setDialog;

    }

    private NumberPicker.OnValueChangeListener diffChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            String [] a=numberPicker_diff.getDisplayedValues();
            getDiff=a[newVal];
        }
    };

    private NumberPicker.OnValueChangeListener modeChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            String[] a= numberPicker_mode.getDisplayedValues();
            getMode=a[newVal];
        }
    };

    private NumberPicker.OnValueChangeListener musicChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            String [] a= numberPicker_music.getDisplayedValues();
            getMusic=a[newVal];
        }
    };



}










